<template>
  <div class="algorithm-config-panel">
    <!-- 算法选择 -->
    <div class="algorithm-selection-section">
      <h3>算法选择</h3>
      <div class="algorithm-cards">
        <div 
          v-for="algorithm in availableAlgorithms" 
          :key="algorithm.type"
          class="algorithm-card"
          :class="{ active: selectedAlgorithm === algorithm.type }"
          @click="selectAlgorithm(algorithm.type)"
        >
          <div class="algorithm-header">
            <h4>{{ algorithm.name }}</h4>
            <el-tag :type="algorithm.complexity" size="small">
              {{ getComplexityText(algorithm.complexity) }}
            </el-tag>
          </div>
          <div class="algorithm-description">
            <p>{{ algorithm.description }}</p>
          </div>
          <div class="algorithm-metrics">
            <div class="metric">
              <span class="metric-label">准确率:</span>
              <span class="metric-value">{{ algorithm.accuracy }}%</span>
            </div>
            <div class="metric">
              <span class="metric-label">性能:</span>
              <span class="metric-value">{{ algorithm.performance }}</span>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 参数配置 -->
    <div class="parameter-config-section">
      <h3>参数配置</h3>
      <el-form :model="config" label-width="140px">
        <el-row :gutter="24">
          <el-col :span="12">
            <el-form-item label="推荐数量">
              <el-input-number 
                v-model="config.recommendCount" 
                :min="1" 
                :max="50" 
                style="width: 100%"
              />
            </el-form-item>
            
            <el-form-item label="相似度阈值">
              <el-slider
                v-model="config.similarityThreshold"
                :min="0"
                :max="1"
                :step="0.1"
                show-input
                :format-tooltip="formatSimilarityTooltip"
              />
            </el-form-item>
            
            <el-form-item label="时间衰减因子">
              <el-slider
                v-model="config.timeDecayFactor"
                :min="0"
                :max="1"
                :step="0.1"
                show-input
                :format-tooltip="formatDecayTooltip"
              />
            </el-form-item>
          </el-col>
          
          <el-col :span="12">
            <el-form-item label="多样性权重">
              <el-slider
                v-model="config.diversityWeight"
                :min="0"
                :max="1"
                :step="0.1"
                show-input
                :format-tooltip="formatDiversityTooltip"
              />
            </el-form-item>
            
            <el-form-item label="新颖性权重">
              <el-slider
                v-model="config.noveltyWeight"
                :min="0"
                :max="1"
                :step="0.1"
                show-input
                :format-tooltip="formatNoveltyTooltip"
              />
            </el-form-item>
            
            <el-form-item label="流行度权重">
              <el-slider
                v-model="config.popularityWeight"
                :min="0"
                :max="1"
                :step="0.1"
                show-input
                :format-tooltip="formatPopularityTooltip"
              />
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-row :gutter="24">
          <el-col :span="12">
            <el-form-item label="启用时间衰减">
              <el-switch v-model="config.enableTimeDecay" />
            </el-form-item>
            
            <el-form-item label="启用冷启动">
              <el-switch v-model="config.enableColdStart" />
            </el-form-item>
          </el-col>
          
          <el-col :span="12">
            <el-form-item label="启用实时更新">
              <el-switch v-model="config.enableRealTimeUpdate" />
            </el-form-item>
            
            <el-form-item label="启用A/B测试">
              <el-switch v-model="config.enableABTest" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </div>

    <!-- 高级配置 -->
    <div class="advanced-config-section" v-if="showAdvancedConfig">
      <h3>高级配置</h3>
      <el-form :model="advancedConfig" label-width="140px">
        <el-row :gutter="24">
          <el-col :span="12">
            <el-form-item label="最小支持度">
              <el-input-number 
                v-model="advancedConfig.minSupport" 
                :min="0" 
                :max="1" 
                :step="0.01"
                style="width: 100%"
              />
            </el-form-item>
            
            <el-form-item label="最小置信度">
              <el-input-number 
                v-model="advancedConfig.minConfidence" 
                :min="0" 
                :max="1" 
                :step="0.01"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
          
          <el-col :span="12">
            <el-form-item label="学习率">
              <el-input-number 
                v-model="advancedConfig.learningRate" 
                :min="0.001" 
                :max="1" 
                :step="0.001"
                style="width: 100%"
              />
            </el-form-item>
            
            <el-form-item label="正则化参数">
              <el-input-number 
                v-model="advancedConfig.regularization" 
                :min="0" 
                :max="1" 
                :step="0.01"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </div>

    <!-- 预设配置 -->
    <div class="preset-config-section">
      <h3>预设配置</h3>
      <div class="preset-buttons">
        <el-button 
          v-for="preset in presetConfigs" 
          :key="preset.name"
          @click="applyPreset(preset)"
          :type="preset.type"
        >
          {{ preset.name }}
        </el-button>
      </div>
    </div>

    <!-- 配置预览 -->
    <div class="config-preview-section">
      <h3>配置预览</h3>
      <div class="config-preview">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="算法类型">
            {{ getAlgorithmName(selectedAlgorithm) }}
          </el-descriptions-item>
          <el-descriptions-item label="推荐数量">
            {{ config.recommendCount }}
          </el-descriptions-item>
          <el-descriptions-item label="相似度阈值">
            {{ config.similarityThreshold }}
          </el-descriptions-item>
          <el-descriptions-item label="多样性权重">
            {{ config.diversityWeight }}
          </el-descriptions-item>
          <el-descriptions-item label="时间衰减">
            {{ config.enableTimeDecay ? '启用' : '禁用' }}
          </el-descriptions-item>
          <el-descriptions-item label="实时更新">
            {{ config.enableRealTimeUpdate ? '启用' : '禁用' }}
          </el-descriptions-item>
        </el-descriptions>
      </div>
    </div>

    <!-- 操作按钮 -->
    <div class="action-buttons">
      <el-button @click="toggleAdvancedConfig">
        {{ showAdvancedConfig ? '隐藏' : '显示' }}高级配置
      </el-button>
      <el-button @click="resetConfig">重置配置</el-button>
      <el-button @click="saveConfig">保存配置</el-button>
      <el-button type="primary" @click="applyConfig" :loading="applying">
        应用配置
      </el-button>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, computed } from 'vue'
import { ElMessage } from 'element-plus'

// Props
const props = defineProps({
  initialConfig: {
    type: Object,
    default: () => ({})
  }
})

// Emits
const emit = defineEmits(['config-changed', 'config-applied'])

// 响应式数据
const applying = ref(false)
const showAdvancedConfig = ref(false)
const selectedAlgorithm = ref('collaborative')

// 基础配置
const config = reactive({
  recommendCount: 10,
  similarityThreshold: 0.7,
  timeDecayFactor: 0.8,
  diversityWeight: 0.3,
  noveltyWeight: 0.2,
  popularityWeight: 0.1,
  enableTimeDecay: true,
  enableColdStart: false,
  enableRealTimeUpdate: true,
  enableABTest: false,
  ...props.initialConfig
})

// 高级配置
const advancedConfig = reactive({
  minSupport: 0.01,
  minConfidence: 0.5,
  learningRate: 0.01,
  regularization: 0.1
})

// 可用算法
const availableAlgorithms = ref([
  {
    type: 'collaborative',
    name: '协同过滤',
    description: '基于用户行为相似性进行推荐，适合有丰富用户行为数据的场景',
    complexity: 'primary',
    accuracy: 85,
    performance: '中等'
  },
  {
    type: 'content',
    name: '内容推荐',
    description: '基于物品特征相似性进行推荐，适合冷启动和新用户场景',
    complexity: 'success',
    accuracy: 78,
    performance: '较快'
  },
  {
    type: 'hybrid',
    name: '混合推荐',
    description: '结合多种推荐算法的优势，提供更准确和多样化的推荐',
    complexity: 'warning',
    accuracy: 89,
    performance: '较慢'
  },
  {
    type: 'deep_learning',
    name: '深度学习',
    description: '使用神经网络模型进行推荐，能够捕捉复杂的用户偏好模式',
    complexity: 'danger',
    accuracy: 92,
    performance: '慢'
  }
])

// 预设配置
const presetConfigs = ref([
  {
    name: '高准确率',
    type: 'primary',
    config: {
      recommendCount: 5,
      similarityThreshold: 0.8,
      diversityWeight: 0.1,
      enableTimeDecay: true
    }
  },
  {
    name: '高多样性',
    type: 'success',
    config: {
      recommendCount: 15,
      similarityThreshold: 0.6,
      diversityWeight: 0.6,
      enableTimeDecay: false
    }
  },
  {
    name: '平衡模式',
    type: 'warning',
    config: {
      recommendCount: 10,
      similarityThreshold: 0.7,
      diversityWeight: 0.3,
      enableTimeDecay: true
    }
  }
])

// 方法
const selectAlgorithm = (algorithmType) => {
  selectedAlgorithm.value = algorithmType
  emit('config-changed', { algorithm: algorithmType, ...config })
}

const getComplexityText = (complexity) => {
  const textMap = {
    'primary': '简单',
    'success': '中等',
    'warning': '复杂',
    'danger': '高级'
  }
  return textMap[complexity] || '未知'
}

const getAlgorithmName = (type) => {
  const algorithm = availableAlgorithms.value.find(alg => alg.type === type)
  return algorithm ? algorithm.name : type
}

const formatSimilarityTooltip = (value) => `${value} 相似度`
const formatDecayTooltip = (value) => `${value} 衰减因子`
const formatDiversityTooltip = (value) => `${value} 多样性`
const formatNoveltyTooltip = (value) => `${value} 新颖性`
const formatPopularityTooltip = (value) => `${value} 流行度`

const toggleAdvancedConfig = () => {
  showAdvancedConfig.value = !showAdvancedConfig.value
}

const applyPreset = (preset) => {
  Object.assign(config, preset.config)
  ElMessage.success(`已应用${preset.name}配置`)
  emit('config-changed', { algorithm: selectedAlgorithm.value, ...config })
}

const resetConfig = () => {
  Object.assign(config, {
    recommendCount: 10,
    similarityThreshold: 0.7,
    timeDecayFactor: 0.8,
    diversityWeight: 0.3,
    noveltyWeight: 0.2,
    popularityWeight: 0.1,
    enableTimeDecay: true,
    enableColdStart: false,
    enableRealTimeUpdate: true,
    enableABTest: false
  })
  selectedAlgorithm.value = 'collaborative'
  ElMessage.success('配置已重置')
}

const saveConfig = () => {
  // 保存配置到本地存储或服务器
  const configData = {
    algorithm: selectedAlgorithm.value,
    ...config,
    advanced: advancedConfig
  }
  localStorage.setItem('recommendationConfig', JSON.stringify(configData))
  ElMessage.success('配置已保存')
}

const applyConfig = async () => {
  applying.value = true
  try {
    // 模拟应用配置
    await new Promise(resolve => setTimeout(resolve, 2000))
    
    const finalConfig = {
      algorithm: selectedAlgorithm.value,
      ...config,
      advanced: showAdvancedConfig.value ? advancedConfig : null
    }
    
    emit('config-applied', finalConfig)
    ElMessage.success('配置应用成功')
  } catch (error) {
    ElMessage.error('配置应用失败')
  } finally {
    applying.value = false
  }
}
</script>

<style scoped>
.algorithm-config-panel {
  padding: 20px 0;
}

.algorithm-selection-section,
.parameter-config-section,
.advanced-config-section,
.preset-config-section,
.config-preview-section {
  margin-bottom: 32px;
}

.algorithm-selection-section h3,
.parameter-config-section h3,
.advanced-config-section h3,
.preset-config-section h3,
.config-preview-section h3 {
  margin: 0 0 16px 0;
  color: #333;
  font-size: 16px;
  font-weight: 600;
  border-bottom: 2px solid #f0f0f0;
  padding-bottom: 8px;
}

/* 算法卡片 */
.algorithm-cards {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
  gap: 16px;
}

.algorithm-card {
  border: 2px solid #f0f0f0;
  border-radius: 8px;
  padding: 16px;
  cursor: pointer;
  transition: all 0.3s ease;
}

.algorithm-card:hover {
  border-color: #409EFF;
  box-shadow: 0 4px 12px rgba(64, 158, 255, 0.1);
}

.algorithm-card.active {
  border-color: #409EFF;
  background: #f0f9ff;
}

.algorithm-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 12px;
}

.algorithm-header h4 {
  margin: 0;
  font-size: 16px;
  font-weight: 600;
  color: #333;
}

.algorithm-description p {
  margin: 0 0 12px 0;
  font-size: 14px;
  color: #666;
  line-height: 1.5;
}

.algorithm-metrics {
  display: flex;
  gap: 16px;
}

.metric {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.metric-label {
  font-size: 12px;
  color: #999;
}

.metric-value {
  font-size: 14px;
  font-weight: 600;
  color: #333;
}

/* 预设按钮 */
.preset-buttons {
  display: flex;
  gap: 12px;
  flex-wrap: wrap;
}

/* 配置预览 */
.config-preview {
  background: #f8f9fa;
  padding: 16px;
  border-radius: 8px;
}

/* 操作按钮 */
.action-buttons {
  display: flex;
  gap: 12px;
  justify-content: center;
  padding-top: 20px;
  border-top: 1px solid #f0f0f0;
}

@media (max-width: 768px) {
  .algorithm-cards {
    grid-template-columns: 1fr;
  }
  
  .action-buttons {
    flex-direction: column;
  }
  
  .action-buttons .el-button {
    width: 100%;
  }
  
  .preset-buttons {
    flex-direction: column;
  }
  
  .preset-buttons .el-button {
    width: 100%;
  }
  
  .algorithm-metrics {
    flex-direction: column;
    gap: 8px;
  }
}
</style>
